package com.arpa.ntocc.common.security.filter;

import com.arpa.core.web.RestFulStatus;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.util.HttpUtil;
import com.arpa.ntocc.common.service.IClientService;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Oauth 授权验证过滤器
 * @author leo
 */
public class PartyFilter extends AdviceFilter {

    static org.apache.logging.log4j.Logger logger = LogManager.getLogger(PartyFilter.class);

    @Autowired
    private IClientService clientService;

    /**
     * 在拦截器链执行之前执行；如果返回true则继续拦截器链；否则中断后续的拦截器链的执行直接返回；进行预处理（如基于表单的身份验证、授权）
     *
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest req, ServletResponse resp) throws IOException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers","*");
        response.setContentType("application/json; charset=utf-8");

        String clientId = request.getHeader("client_id");//客户端应用ID
        String clientSecret = request.getHeader("client_secret");//客户端应用安全码
        if (!StringUtils.isNoneBlank(clientId, clientSecret)) {
            response.getWriter().write(Result.error(RestFulStatus.OAUTH2_INVALID_CLIENT).toString());
            return false;
        }
        if (!clientService.verificationIdAndSecret(clientId, clientSecret)) {
            response.getWriter().write(Result.error(RestFulStatus.OAUTH2_INVALID_CLIENT).toString());
            return false;
        }

        request.setAttribute("ip", HttpUtil.getIpAddress(request));

        return true;
    }

}
